package com.physique.tea.Service.Impl;

import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.physique.tea.vo.TcmData;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;

@Service
public class TcmDataService {

    // 中医九种体质白名单（保持不变）
    private static final List<String> VALID_CONSTITUTIONS = Arrays.asList(
            "平和质", "气虚质", "阳虚质", "阴虚质",
            "痰湿质", "湿热质", "血瘀质", "气郁质", "特禀质"
    );

    /**
     * 处理项目内的CSV文件
     */
    public Map<String, Map<String, Integer>> processInternalCsv() throws Exception {
        // 从classpath读取CSV文件
        try (InputStream inputStream = new ClassPathResource("static/tcm_sample_data_grouped(1).csv").getInputStream()) {
            return processCsvStream(inputStream);
        }
    }

    /**
     * 通用CSV处理逻辑（供上传和内置文件共用）
     */
    private Map<String, Map<String, Integer>> processCsvStream(InputStream inputStream) throws Exception {
        // 初始化结果容器（保持顺序：幼年→青年→中年→老年）
        Map<String, Map<String, Integer>> result = new LinkedHashMap<>();
        Arrays.asList("幼年", "青年", "中年", "老年").forEach(ageGroup ->
                result.put(ageGroup, new HashMap<>())
        );

        try (Reader reader = new InputStreamReader(inputStream)) {
            // CSV解析配置（保持不变）
            HeaderColumnNameMappingStrategy<TcmData> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(TcmData.class);

            CsvToBean<TcmData> csvToBean = new CsvToBeanBuilder<TcmData>(reader)
                    .withType(TcmData.class)
                    .withMappingStrategy(strategy)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();

            // 逐行处理数据（保持不变）
            for (TcmData data : csvToBean) {
                validateData(data);
                String ageGroup = determineAgeGroup(data.getAge());
                result.get(ageGroup).merge(
                        data.getConstitution(),
                        data.getCount(),
                        Integer::sum
                );
            }
        }
        return result;
    }

    // 年龄分段逻辑（保持不变）
    private String determineAgeGroup(Integer age) {
        if (age == null) return "未知";
        if (age <= 35) {
            return "青年";
        } else if (age <= 59) {
            return "中年";
        } else {
            return "老年";
        }
    }
    // 数据验证（保持不变）
    private void validateData(TcmData data) throws Exception {
        if (data.getAge() == null || data.getAge() < 0) {
            throw new Exception("无效年龄值: " + data.getAge());
        }
        if (data.getCount() == null || data.getCount() < 0) {
            throw new Exception("无效人数值: " + data.getCount());
        }
        if (!VALID_CONSTITUTIONS.contains(data.getConstitution())) {
            throw new Exception("无效体质类型: " + data.getConstitution());
        }
    }
}